<template>
  <div>
    <div class="table-container">
      <h3 class="section-title">
        教师 & 助教
      </h3>
      <hr class="divider">
      <div class="card shadow-sm border-0 rounded-4 mb-4">
        <div class="card-body d-flex align-items-center py-4">
          <img
            src="https://i.pravatar.cc/300"
            class="rounded-circle shadow-sm me-4"
            style="width: 56px; height: 56px; object-fit: cover"
          >
          <div>
            <h5
              class="mb-1 fw-bold"
              style="letter-spacing: 1px"
            >
              {{ teacherDisplay }}
            </h5>
            <div class="text-muted small">
              主讲教师
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="table-container">
      <h3 class="section-title mb-3 text-dark">
        课程信息
      </h3>
      <hr class="divider">
      <div class="row g-4">
        <!-- 基本信息 -->
        <div class="col-12 col-md-5">
          <div
            class="card border-0 shadow rounded-4 h-100 px-0 py-0"
            style="background: #fff"
          >
            <div class="px-4 py-4">
              <div class="d-flex align-items-center mb-2">
                <div class="flex-grow-1">
                  <div
                    class="fs-5 fw-bold mb-1 text-dark"
                    style="letter-spacing: 1px"
                  >
                    {{ course.courseName }}
                  </div>
                  <div class="small mb-2 text-dark">
                    课程号：{{ course.courseId }}
                  </div>
                </div>
              </div>
              <hr class="my-3">
              <div class="mb-2">
                <span class="fw-semibold text-dark">教师：</span><span class="text-dark">{{ teacherDisplay }}</span>
              </div>
              <div class="mb-2">
                <span class="fw-semibold text-dark">职称：</span><span class="text-dark">{{ course.teacher?.title || '副教授' }}</span>
              </div>
              <div class="mb-2">
                <span class="fw-semibold text-dark">邮箱：</span><span class="text-dark">{{ course.teacher?.email || 'teacher@example.com' }}</span>
              </div>
              <div>
                <span class="fw-semibold text-dark">学院：</span><span class="text-dark">{{ course.teacher?.college || '软件学院' }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 课程简介 -->
        <div class="col-12 col-md-7">
          <div
            class="card border-0 shadow rounded-4 h-100 px-0 py-0"
            style="background: #fff"
          >
            <div class="px-4 py-4">
              <!-- 课程简介（居中） -->
              <div class="text-center mb-3">
                <div class="d-flex justify-content-center align-items-center mb-2">
                  <span style="font-size: 1.5rem; color: #104f91; margin-right: 8px">&#8505;</span>
                  <div class="fw-bold fs-5 text-dark">
                    课程简介
                  </div>
                </div>
                <div
                  class="text-dark"
                  style="font-size: 1.05rem;"
                >
                  {{ course.course || '暂无' }}
                </div>
              </div>

              <!-- 分割线 -->
              <hr class="my-3">

              <!-- 学习要求（标题和内容都居中） -->
              <div class="text-center">
                <div class="d-flex justify-content-center align-items-center mb-1">
                  <span style="font-size: 1.3rem; color: #104f91; margin-right: 8px">&#8505;</span>
                  <div class="fw-semibold fs-5 text-dark">
                    学习要求：
                  </div>
                </div>
                <div
                  class="text-dark"
                  style="font-size: 1.05rem;"
                >
                  {{ course.teachingGoal || '暂无学习要求' }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="table-container mt-5">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <h3 class="section-title mb-0 text-dark">
          课程章节
        </h3>
        <button
          v-if="userRole === 'teacher'"
          class="btn btn-success btn-sm px-3 btn-download"
          style="font-size: 1.15rem"
          @click="showCreateChapterModal = true"
        >
          创建
        </button>
      </div>
      <hr class="divider">
      <div
        class="card shadow border-0 rounded-4"
        style="overflow: hidden"
      >
        <table
          class="table align-middle mb-0 custom-table"
          style="background: #fff; font-size: 1.13rem"
        >
          <thead>
            <tr style="background: #007bff">
              <th
                scope="col"
                class="fw-semibold text-white"
                style="font-size: 1.18rem; letter-spacing: 1px"
              >
                章节序号
              </th>
              <th
                scope="col"
                class="fw-semibold text-white"
                style="font-size: 1.18rem"
              >
                章节名称
              </th>
              <th
                scope="col"
                class="fw-semibold text-white"
                style="font-size: 1.18rem"
              >
                操作
              </th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="(chapter, i) in chapters"
              :key="chapter.chapterId"
              style="border-bottom: 1.5px solid #eef3fa"
            >
              <td
                class="text-dark"
                style="font-size: 1.13rem"
              >
                第{{ i + 1 }}章
              </td>
              <td
                class="text-dark"
                style="font-size: 1.13rem"
              >
                {{ chapter.chapterName }}
              </td>
              <td>
                <button
                  v-if="userRole === 'student'"
                  class="btn btn-primary btn-sm btn-download"
                  style="margin-right: 8px; font-size: 1.08rem"
                  @click="goToStudy(chapter.chapterId)"
                >
                  去学习
                </button>
                <button
                  v-if="userRole === 'teacher'"
                  class="btn btn-danger btn-sm btn-delete"
                  style="font-size: 1.08rem"
                  @click="deleteChapter(chapter.chapterId)"
                >
                  删除
                </button>
              </td>
            </tr>
            <tr v-if="chapters.length === 0">
              <td
                colspan="3"
                class="text-dark text-center py-4 bg-light"
                style="font-size: 1.08rem"
              >
                暂无章节
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 创建章节弹窗 -->
    <div
      v-if="showCreateChapterModal"
      class="modal-backdrop"
    >
      <div class="modal-content-box">
        <h5 class="mb-3">
          创建新章节
        </h5>
        <input
          v-model="newChapterName"
          class="form-control mb-3"
          placeholder="请输入章节名称"
          @keyup.enter="createChapter"
        >
        <div class="d-flex justify-content-end gap-2">
          <button
            class="btn btn-secondary btn-sm"
            @click="showCreateChapterModal = false"
          >
            取消
          </button>
          <button
            class="btn btn-success btn-sm"
            @click="createChapter"
          >
            创建
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, computed } from 'vue'
  import axios from 'axios'

  const route = useRoute()
  const courseId = route.params.id
  const teacherNames = ref([])
  // 定义响应式变量存储课程数据
  const course = ref({})
  // ...已有import
  import { useRoute } from 'vue-router'
  import { useRouter } from 'vue-router'
  import { useUserStore } from '@/stores/userStore'

  const userRole = ref('') // 保存后端返回的角色
  const router = useRouter()
  const userStore = useUserStore()
  const userId = userStore.user?.userId || ''

  function goToStudy(chapterId) {
    axios
      .post(`/api/progress/chapters`, {
        userId: userId,
        chapterId: chapterId,
        status: 'completed'
      })
      .then(() => {
        console.log('章节学习记录已更新')
        // 跳转到学习页面
        router.push(`/course/${courseId}/material/by-chapter?chapterId=${chapterId}`)
      })
      .catch((err) => {
        router.push(`/course/${courseId}/material/by-chapter?chapterId=${chapterId}`)
      })
    router.push(`/course/${courseId}/material/by-chapter`)
  }
  async function fetchUserRole() {
    try {
      const res = await axios.get('/api/exercises/role', {
        params: {
          courseId,
          userId,
        },
      })
      userRole.value = res.data
      console.log('身份识别结果:', userRole.value)
    } catch (err) {
      console.error('获取用户身份失败', err)
      userRole.value = 'undefined'
    }
  }
  onMounted(fetchUserRole)
  const chapters = ref([])
  const showCreateChapterModal = ref(false)
  const newChapterName = ref('')

  // 获取全部章节
  async function fetchChapters() {
    try {
      const res = await axios.get(`/api/chapters/course/${courseId}`)
      chapters.value = res.data
    } catch (err) {
      console.error('获取章节失败：', err)
      chapters.value = []
    }
  }

  // 创建章节
  async function createChapter() {
    const name = newChapterName.value.trim()
    if (!name) return

    try {
      // 1. 传递 course 对象，包含 courseId
      await axios.post('/api/chapters', {
        chapterId: 'CH' + Date.now(),
        chapterName: name,
        course: { courseId },
      })
      showCreateChapterModal.value = false
      newChapterName.value = ''
      await fetchChapters()
    } catch (err) {
      alert('创建失败: ' + (err.response?.data?.message || err.message))
    }
  }

  // 删除章节
  async function deleteChapter(chapterId) {
    if (!confirm('确认删除该章节？')) return
    try {
      await axios.delete(`/api/chapters/${chapterId}`)
      await fetchChapters()
    } catch (err) {
      alert('删除失败: ' + (err.response?.data?.message || err.message))
    }
  }

  // 页面挂载时加载章节
  onMounted(async () => {
    // ...你已有的 onMounted 代码
    await fetchChapters()
  })

  const teacherDisplay = computed(() =>
    teacherNames.value.length > 0 ? teacherNames.value.join(', ') : '李老师'
  )
  // 页面挂载时获取课程信息
  onMounted(async () => {
    try {
      const response = await axios.get(`/api/courses/${courseId}/teachers`)
      const res = await axios.get(`/api/courses/${courseId}`)
      teacherNames.value = [...(response.data.data || [])]
      // console.log(typeof teacherNames.value)
      // console.log(teacherNames.value)
      course.value = res.data.data
      // console.log(course.value)
    } catch (err) {
      console.error('获取课程信息失败：', err)
    }
  })
</script>

<style scoped>
  .divider {
    border: none;
    height: 1px;
    background-color: #9d9d9d;
    margin: 8px 0 16px 0;
    border-radius: 4px;
  }

  .section-title {
    font-size: 35px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #333;
    text-align: left;
  }

  .table-container {
    max-width: 80vw; /* 根据需要缩放，比如 600px、500px */
    margin: 0 auto;
  }

  /* 字体变大 */
  .table-cards th,
  .table-cards td {
    font-size: 18px;
    padding: 1rem;
  }

  /* 头像样式 */
  .avatar {
    border-radius: 50%;
    width: 64px;
    height: 64px;
    object-fit: cover;
  }

  /* 媒体文本样式 */
  .media-body h6 {
    font-size: 18px;
    margin-bottom: 4px;
  }

  .media-body span {
    font-size: 16px;
    color: #777;
  }

  .modal-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.4);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }
  .modal-content-box {
    background: #fff;
    padding: 24px 20px;
    border-radius: 8px;
    min-width: 320px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  }
  /* 你可以加到全局样式里 */
  .modal-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(33, 37, 41, 0.25) !important;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }

  .modal-content-box {
    /* 卡片外观已加在上面 */
  }

  .card.rounded-4 {
    border-radius: 1.25rem !important;
    box-shadow: 0 4px 24px 0 rgba(33, 37, 41, 0.1) !important;
    overflow: hidden;
  }
  .table {
    border-radius: 1.25rem !important;
    overflow: hidden;
  }
  .table th:first-child,
  .table td:first-child {
    border-top-left-radius: 1.1rem !important;
  }
  .table th:last-child,
  .table td:last-child {
    border-top-right-radius: 1.1rem !important;
  }
  .btn-download {
    background-color: #28a745; /* 绿色 */
    color: #fff;
    border: none;
    border-radius: 10px;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }

  .btn-download:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 10px rgba(40, 167, 69, 0.3);
  }

  .btn-delete {
    background-color: #dc3545; /* 红色 */
    color: #fff;
    border: none;
    border-radius: 10px;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }

  .btn-delete:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 10px rgba(220, 53, 69, 0.3);
  }
</style>
